package isp.apps.example.shoppingcart.action;

import isp.apps.example.shoppingcart.domain.Item;
import isp.apps.example.shoppingcart.domain.ShoppingCartValidator;
import isp.apps.example.shoppingcart.persistence.ItemDirectory;
import isp.apps.example.shoppingcart.persistence.factory.ItemPersistenceFactory;
import isp.apps.example.shoppingcart.domain.ShoppingCart;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;



public class UpdateCartAction
  extends ShoppingAction
{
  private Map itemsMap;

  private ItemDirectory iDir;

  private Set entrySet;

  private String key, value;

  public UpdateCartAction()
  {
  }

  public Map getItemsMap()
  {
    if (itemsMap == null)
      itemsMap = new HashMap();
    return itemsMap;
  }

  public String execute()
  {
    validate();
    if (hasActionErrors())
      return INPUT;
    addNewItemsToCart();
    return SUCCESS;
  }

  public void addNewItemsToCart()
  {
    //System.out.println("itemsMap = " + itemsMap);
    //System.out.println("item 1 quantity:" + ((String[])itemsMap.get("1"))[0]);

    ShoppingCart sc = getCart();
    for (Iterator iter = entrySet.iterator(); iter.hasNext(); )
    {
      Map.Entry e = (Map.Entry) iter.next();
      key = (String) (e.getKey());
      value = (String) (e.getValue());
      key = key.trim();
      value = value.trim();
      // if value >= 1 and not empty
      if ((!value.equals("")) &&
          (new Integer(value).compareTo(new Integer("0")) > 0))
      {
        Item i = iDir.getItem(new Integer(key));
        //System.out.println("UpdateCartAction item = " + i);
        if (i != null)
          sc.addItem(i, Integer.parseInt(value));
      }
    }
  }

  public void validate()
  {
    ShoppingCartValidator scv = new ShoppingCartValidator();
    if (itemsMap == null)
    {
      addActionError("Items map is null");
      return;
    }
    entrySet = itemsMap.entrySet();
    iDir = ItemPersistenceFactory.getItemDirectory();
    for (Iterator iter = entrySet.iterator(); iter.hasNext(); )
    {
      Map.Entry e = (Map.Entry) iter.next();
      key = (String) (e.getKey());
      value = (String) (e.getValue());
      if ((key = scv.checkNumber(key)) == null)
      {
        addActionError("Items map corrupted!");
        return;
      }
      if ((value == null) || value.equals(""))
         continue;
      if ((scv.checkNumber(value)) == null)
      {
        Item i = iDir.getItem(new Integer(key));
        addActionError("Item \"" + i.getName() +
                       "\" has invalid quantity: \"" + value + "\"");
        return;
      }
      value = scv.checkNumber(value);
    }
  }
}
